<?php

namespace common\validators;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * MobileValidator validates that the attribute value is a valid mobile number.
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class MobileValidator extends \yii\validators\Validator {

    /**
     * @var string the regular expression used to validate the attribute value.
     * @see http://www.regular-expressions.info/email.html
     */
    public $pattern = '/1[3456789]{1}\d{9}$/';

    /**
     * @var bool whether the comparison is strict (both type and value must be the same)
     */
    public $strict = false;

    /**
     * {@inheritdoc}
     */
    public function init() {
        parent::init();
        if ($this->message === null) {
            $this->message = '{attribute}格式不正确';
        }
        if (!$this->pattern) {
            $this->pattern = ArrayHelper::getValue(Yii::$app->params, ['format_pattern', 'mobile']);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function validateAttribute($model, $attribute) {
        if (!$this->isMobile($model->$attribute)) {
            $this->addError($model, $attribute, $this->message);
            return;
        }
        parent::validateAttribute($model, $attribute);
    }

    /**
     * {@inheritdoc}
     */
    protected function validateValue($value) {
        return $this->isMobile($value) ? null : [$this->message, []];
    }

    /**
     * @param mixed $value the data value to be checked.
     */
    private function isMobile($value) {
        if (strlen($value) !== 11) {
            $this->message .= ' 必需为11位数字';
            return false;
        }
        if (!preg_match($this->pattern, $value)) {
            return false;
        }
        return true;
    }

}
